package cn.bluethink.view;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static cn.bluethink.utile.HttpUtil.sendGet;

public class RegisteredView extends JFrame {

    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();

    JLabel l1 = new JLabel("名称");
    JLabel l2 = new JLabel("性别");
    JLabel l3 = new JLabel("年龄");
    JLabel l4 = new JLabel("密码");

    JTextField f1 = new JTextField();
    JTextField f2 = new JTextField();
    JTextField f3 = new JTextField();
    JPasswordField  f4 = new JPasswordField ();

    JButton b1 = new JButton("提交");

    public Map<String,String> buildRegisteredView(){
        final Map<String,String> res = new HashMap<>();
        this.setLayout(new BorderLayout());
        p1.setLayout(new GridLayout(4,4));
        p1.add(l1);
        p1.add(f1);

        p1.add(l2);
        p1.add(f2);

        p1.add(l3);
        p1.add(f3);

        p1.add(l4);
        p1.add(f4);

        this.add(p1,BorderLayout.NORTH);
        p2.add(b1,BorderLayout.CENTER);
        this.add(p2,BorderLayout.CENTER);
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                String result = "";
                res.put("name",f1.getText());
                res.put("sex",f2.getText());
                res.put("age",f3.getText());
                res.put("password",f4.getText());
                try {
                    String name = URLEncoder.encode(f1.getText(),"utf-8");
                    String sex = URLEncoder.encode(f2.getText(),"utf-8");
                    result = sendGet("http://localhost/user/registered","age=" + f3.getText()+"&password="+f4.getText() + "&name=" + name + "&sex=" + sex);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                res.put("result",result);
                close();
            }
        });
        this.setSize(250,200);
        this.setVisible(true);
        return res;
    }

    /**
     * 关闭当前的窗体
     */
    private void close() {
        this.dispose();
    }

}
